package com.noahsloan.nutils.streams;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.noahsloan.nutils.InToOut;

/**
 * Stream that counts the number of bytes written to it.
 * 
 * @author noah
 * 
 */
public class CountingOutputStream extends FilterOutputStream {

    private volatile transient long count;

    /**
     * Discards all bytes written.
     */
    public CountingOutputStream() {
        this(new NullOutputStream());
    }

    /**
     * Writes to the given stream, counting the bytes.
     * 
     * @param out
     */
    public CountingOutputStream(OutputStream out) {
        super(out);
    }

    @Override
    public void write(int b) throws IOException {
        super.write(b);
        count++;
    }

    @Override
    public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        super.write(b, off, len);
        count += len;
    }

    public long getCount() {
        return count;
    }

    public void setCount(long count) {
        this.count = count;
    }

    public static long count(InputStream in) throws IOException {
        CountingOutputStream count = new CountingOutputStream();
        new InToOut(in, count).connect();
        return count.getCount();
    }
}
